package com.wande.dataplatform.filecollection.alert;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 告警服务
 * 支持企业微信、钉钉等告警通知
 *
 * @author wande
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AlertService {

    @Value("${file-collection.alert.wechat-webhook:}")
    private String wechatWebhook;

    @Value("${file-collection.alert.dingtalk-webhook:}")
    private String dingtalkWebhook;

    @Value("${file-collection.alert.enabled:false}")
    private Boolean alertEnabled;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 发送告警
     *
     * @param alert 告警信息
     */
    public void sendAlert(Alert alert) {
        if (!alertEnabled) {
            log.debug("Alert is disabled, skip sending: {}", alert.getTitle());
            return;
        }

        try {
            // 发送企业微信告警
            if (cn.hutool.core.util.StrUtil.isNotBlank(wechatWebhook)) {
                sendWechatAlert(alert);
            }

            // 发送钉钉告警
            if (cn.hutool.core.util.StrUtil.isNotBlank(dingtalkWebhook)) {
                sendDingtalkAlert(alert);
            }

            log.info("Alert sent: {}", alert.getTitle());

        } catch (Exception e) {
            log.error("Failed to send alert: {}", alert.getTitle(), e);
        }
    }

    /**
     * 发送企业微信告警
     */
    private void sendWechatAlert(Alert alert) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("msgtype", "markdown");

            Map<String, String> markdown = new HashMap<>();
            markdown.put("content", buildWechatMarkdown(alert));
            message.put("markdown", markdown);

            String response = HttpUtil.post(wechatWebhook, JSONUtil.toJsonStr(message));
            log.debug("Wechat alert response: {}", response);

        } catch (Exception e) {
            log.error("Failed to send wechat alert", e);
        }
    }

    /**
     * 构建企业微信Markdown消息
     */
    private String buildWechatMarkdown(Alert alert) {
        StringBuilder sb = new StringBuilder();
        sb.append("## ").append(alert.getTitle()).append("\n\n");
        sb.append("**级别**: <font color=\"").append(getLevelColor(alert.getLevel())).append("\">")
          .append(alert.getLevel()).append("</font>\n\n");
        sb.append("**时间**: ").append(alert.getTimestamp()).append("\n\n");
        sb.append("**内容**: ").append(alert.getContent()).append("\n\n");

        if (alert.getDetails() != null && !alert.getDetails().isEmpty()) {
            sb.append("**详情**:\n");
            alert.getDetails().forEach((key, value) -> 
                sb.append("- ").append(key).append(": ").append(value).append("\n"));
        }

        return sb.toString();
    }

    /**
     * 发送钉钉告警
     */
    private void sendDingtalkAlert(Alert alert) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("msgtype", "markdown");

            Map<String, String> markdown = new HashMap<>();
            markdown.put("title", alert.getTitle());
            markdown.put("text", buildDingtalkMarkdown(alert));
            message.put("markdown", markdown);

            String response = HttpUtil.post(dingtalkWebhook, JSONUtil.toJsonStr(message));
            log.debug("Dingtalk alert response: {}", response);

        } catch (Exception e) {
            log.error("Failed to send dingtalk alert", e);
        }
    }

    /**
     * 构建钉钉Markdown消息
     */
    private String buildDingtalkMarkdown(Alert alert) {
        StringBuilder sb = new StringBuilder();
        sb.append("## ").append(alert.getTitle()).append("\n\n");
        sb.append("**级别**: ").append(alert.getLevel()).append("\n\n");
        sb.append("**时间**: ").append(alert.getTimestamp()).append("\n\n");
        sb.append("**内容**: ").append(alert.getContent()).append("\n\n");

        if (alert.getDetails() != null && !alert.getDetails().isEmpty()) {
            sb.append("**详情**:\n\n");
            alert.getDetails().forEach((key, value) -> 
                sb.append("- ").append(key).append(": ").append(value).append("\n\n"));
        }

        return sb.toString();
    }

    /**
     * 获取级别颜色
     */
    private String getLevelColor(String level) {
        switch (level.toUpperCase()) {
            case "ERROR":
            case "CRITICAL":
                return "warning";
            case "WARNING":
                return "comment";
            case "INFO":
            default:
                return "info";
        }
    }

    /**
     * 发送任务失败告警
     */
    public void sendTaskFailureAlert(Long taskId, String ruleName, String errorMessage) {
        Alert alert = new Alert();
        alert.setTitle("文件采集任务失败");
        alert.setLevel("ERROR");
        alert.setContent("任务执行失败，请及时处理");
        alert.setTimestamp(LocalDateTime.now().format(FORMATTER));

        Map<String, Object> details = new HashMap<>();
        details.put("任务ID", taskId);
        details.put("采集规则", ruleName);
        details.put("错误信息", errorMessage);
        alert.setDetails(details);

        sendAlert(alert);
    }

    /**
     * 发送数据质量告警
     */
    public void sendDataQualityAlert(Long taskId, double failureRate) {
        Alert alert = new Alert();
        alert.setTitle("数据质量告警");
        alert.setLevel("WARNING");
        alert.setContent(String.format("数据校验失败率过高: %.2f%%", failureRate * 100));
        alert.setTimestamp(LocalDateTime.now().format(FORMATTER));

        Map<String, Object> details = new HashMap<>();
        details.put("任务ID", taskId);
        details.put("失败率", String.format("%.2f%%", failureRate * 100));
        alert.setDetails(details);

        sendAlert(alert);
    }

    /**
     * 发送系统资源告警
     */
    public void sendResourceAlert(String resourceType, double usagePercent) {
        Alert alert = new Alert();
        alert.setTitle("系统资源告警");
        alert.setLevel("WARNING");
        alert.setContent(String.format("%s使用率过高: %.2f%%", resourceType, usagePercent));
        alert.setTimestamp(LocalDateTime.now().format(FORMATTER));

        Map<String, Object> details = new HashMap<>();
        details.put("资源类型", resourceType);
        details.put("使用率", String.format("%.2f%%", usagePercent));
        alert.setDetails(details);

        sendAlert(alert);
    }

    /**
     * 告警信息
     */
    @Data
    public static class Alert {
        private String title;
        private String level;
        private String content;
        private String timestamp;
        private Map<String, Object> details;
    }
}
